//
//  LabelExtension.swift
//  SwiftLearning
//
//  Created by 黄龙 on 2024/1/19.
//

import Foundation
import UIKit

extension UILabel{
    func addTextShadow(title:String,color:UIColor,offset:CGSize=CGSize(width: 2, height: 2),radius:CGFloat = 6){
        let shadow = NSShadow()
        shadow.shadowBlurRadius = radius
        shadow.shadowOffset = offset
        shadow.shadowColor = color
        let attr = NSMutableAttributedString(string: title)
        attr.addAttributes([NSAttributedString.Key.shadow : shadow], range: NSMakeRange(0, attr.length))
        self.attributedText = attr
    }
    
    ///生成渐变颜色图片
    func getGradientImage(colors:[CGColor],startPoint:CGPoint?=nil,endPoint:CGPoint?=nil,locations:[CGFloat]?=nil) -> UIImage{
        let size = self.bounds.size
        UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
        guard let context = UIGraphicsGetCurrentContext() else{return UIImage()}
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        ///设置渐变颜色
        let gradientRef = CGGradient(colorsSpace: colorSpace, colors: colors as CFArray, locations: locations)!
//locations = [0.0~1.0]
        var startXY = CGPoint(x: size.width/2, y: 0)
        if let startPos = startPoint{
            startXY = startPos
        }
        var endXY = CGPoint(x: size.width/2, y: size.height)
        if let endPos = endPoint{
            endXY = endPos
        }
//startPoint,endPoint(x:0~width,y:0~height)
        context.drawLinearGradient(gradientRef, start: startXY, end: endXY, options: CGGradientDrawingOptions(arrayLiteral: .drawsBeforeStartLocation,.drawsAfterEndLocation))
        let gradientImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return gradientImage ?? UIImage()
    }
}
